<?php

namespace app\common\controller;

use think\exception\HttpResponseException;
use app\common\controller\Base;
use app\common\exception\MyException;
use app\common\service\sys\ClientService;
use app\common\service\sys\DictService;
use app\common\service\sys\UserRoleMenusService;
use app\common\service\sys\UserService;

/**
 * 后台权限控制器基类
 * @author kaige
 * @copyright ©2022 泉州市盛筑信息科技有限公司 版权所有
 * @update 2022-04-25 
 */
class Basic extends Base
{
    /**
     * 设置当前服务
     */
    protected $service;
    /**
     * 用户信息
     */
    protected $user;
    /**
     * 节点
     */
    protected $node;
    /**
     * 字典
     */
    protected $sysdict;
    /**
     * 模块(表)名称
     */
    protected $table_name;
    /**
     * 模块ID
     */
    protected $table_moduId;
    /**
     * 初始化 不能用 return 只能exit
     * @return void
     */
    protected function initialize()
    {
        parent::initialize();
        //验证签名
        $appid = $this->request->header('Kg-Appid');
        if (empty($appid)) {
            throw new MyException(['code' => 1002]);
        }
        // 实时数据
        $app = (new ClientService())->getInfoByWhere(['app_id' => $appid]);
        // 是否存在
        if (empty($app)) {
            throw new MyException(['code' => 2001]);
        }
        // 状态
        if (empty($app) || $app['status'] != 1) {
            throw new MyException(['code' => 2002]);
        }
        // 客户端应用ID
        // $this->request->client_appid = $appid;

        $appsignwhite = config("kaige.app_sign_white_url");
        list($module, $controller, $action) = [app('http')->getName(), $this->request->controller(), $this->request->action()];
        $node = $module . '/' . $controller . '/' . strtolower($action);
        $node = parseNodeStr($node);
        // throw new MyException(['code' => 1004,'msg'=>$node]); //调试用
        $this->node = $node;

        // 免签白名单
        $whilesign = false;
        if ($node && $appsignwhite && in_array($node, $appsignwhite)) {
            $whilesign = true;
        }

        // 接口签名认证
        if (config("kaige.app_sign_auth_on") === true && $whilesign === false) {
            // app端生成的签名
            $param = $this->request->param();
            $sign  = $this->request->param("signature"); //前端过来的是signature
            unset($param['signature']);
            if (isset($param['_'])) { // jquery ajax cache:false 会加这个玩意
                unset($param['_']);
            }
            if (empty($sign)) {
                throw new MyException(['code' => 2003, 'msg' => $node]);
            }
            //数组排序
            ksort($param);
            foreach ($param as $k9 => &$v9) { //一层数组排一下序
                if (is_array($v9)) {
                    ksort($v9);
                }
            }
            $str = http_build_query($param);
            $sign1 = md5(sha1($str) . $app['app_salt']);
            if ($sign != $sign1) {
                throw new MyException(['code' => 2004]);
            }
        }

        $token = $this->request->header('Kg-Token');
        if (empty($token) || $token == 'false' || $token === false) {
            throw new MyException(['code' => 2101]);
        }

        //验证身份（登录）
        $user = (new UserService())->checkAdmin($token, _gip());
        $this->user = $user['user'];

        //判断当前是否有权限操作
        $urmService = new UserRoleMenusService();
        $permRe = $urmService->checkPerm($this->user['id'], $node);
        if (!$permRe['status']) {
            throw new MyException(['code' => 2005]);
        }

        //取出字典
        $this->sysdict = DictService::getDictAll(env('COMPANY_ID', 11)); //默认 盛筑科技 ID 11
        //操作日志事件
        $param = $this->request->param();
        url_decode($param);
        //删除密码
        if (isset($param['password'])) unset($param['password']);
        if (isset($param['pwd'])) unset($param['pwd']);
        //用户事件
        event('UserLog', [$this->user, $this->node, time(), _gip(), $action, json_encode($param) . ',ON-' . getOS() . '-' . getBrowser()]);
    }

    /**
     * 重定向跳转
     */
    protected function redirect(...$args)
    {
        throw new HttpResponseException(redirect(...$args));
    }
}
